package org.quickbundle.orgauth.rmuser.web;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.quickbundle.base.beans.factory.RmBeanFactory;
import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.config.RmConfig;
import org.quickbundle.modules.code.rmcodetype.util.IRmCodeTypeConstants;
import org.quickbundle.orgauth.IOrgauthConstants;
import org.quickbundle.orgauth.cache.RmAuthorizeCache;
import org.quickbundle.orgauth.custom.impl.RmCustomOrgService;
import org.quickbundle.orgauth.rmauthorize.vo.RmAuthorizeVo;
import org.quickbundle.orgauth.rmparty.service.IRmPartyService;
import org.quickbundle.orgauth.rmparty.util.IRmPartyConstants;
import org.quickbundle.orgauth.rmpartyrelation.service.impl.RmPartyRelationService;
import org.quickbundle.orgauth.rmpartyrelation.vo.RmPartyRelationVo;
import org.quickbundle.orgauth.rmrole.service.IRmRoleService;
import org.quickbundle.orgauth.rmuser.service.IRmUserService;
import org.quickbundle.orgauth.rmuser.util.IRmUserConstants;
import org.quickbundle.orgauth.rmuser.vo.RmUserVo;
import org.quickbundle.orgauth.rmuseronlinerecord.service.IRmUserOnlineRecordService;
import org.quickbundle.orgauth.rmuseronlinerecord.util.IRmUserOnlineRecordConstants;
import org.quickbundle.orgauth.rmuseronlinerecord.util.RmUserOnlineRecordException;
import org.quickbundle.orgauth.rmuseronlinerecord.vo.RmUserOnlineRecordVo;
import org.quickbundle.orgauth.rmuseronlinerecord.web.RmUserOnlineRecordAction;
import org.quickbundle.orgauth.util.RmOrgAuthSqlHelper;
import org.quickbundle.project.IGlobalConstants;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.cache.RmSqlCountCache;
import org.quickbundle.project.common.vo.RmCommonVo;
import org.quickbundle.tools.helper.RmJspHelper;
import org.quickbundle.tools.helper.RmPopulateHelper;
import org.quickbundle.tools.helper.RmSqlHelper;
import org.quickbundle.tools.helper.RmStringHelper;
import org.quickbundle.tools.helper.RmVoHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dfhc.ISystemConstant;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.pub.service.PubParamService;
import com.dfhc.rm.user.IUserConstants;
import com.dfhc.rm.user.service.UserService;
import com.dfhc.rm.user.vo.UserVo;
import com.dfhc.util.JspHelper;
import com.dfhc.util.StringHelper;

/**
 * @author ASUS
 * 会员列表(例子)
 */
@Controller
@RequestMapping(value = "/newOnlineRmUser")
public class newOnlineRmUserController extends RmUserOnlineRecordAction implements IRmUserOnlineRecordConstants {
	@Autowired
	private UserService userService;
	@Autowired
	private IRmUserService iRmUserService;
	@Autowired
	private PubParamService pubParamService;
	@Autowired
	private IRmRoleService roleService;
	@Autowired
	private RmPartyRelationService rmPartyRelationService;
	@Autowired
	private IRmUserOnlineRecordService service;
	/**
     * 简单查询，分页显示，支持表单回写
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "")
    public String list(Model model, HttpServletRequest request) {
    	model.addAttribute(ISystemConstant.QUERY_STRING, request.getQueryString());//全部参数
    	Map<String, Object> searchPara = getQueryByCondition(request);  //从request中获得查询条件
    	String condition = request.getParameter(DEFAULT_CONDITION_KEY_ARRAY[0]);
    	String queryCondition = " " + DEFAULT_CONDITION_KEY_ARRAY[0] + "='" + condition + "'";
	        request.setAttribute(REQUEST_QUERY_CONDITION, queryCondition);
	        
	        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
	            request.setAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
	        }
	        
	        queryCondition = getQueryCondition(request);  //从request中获得查询条件
	        RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
	        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
	        List<RmUserOnlineRecordVo> beans = service.queryByCondition(queryCondition, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
	        
	        
	        //beans = service.queryByCondition(queryCondition, orderStr);  //查询全部,带排序
	        RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
	        model.addAttribute(REQUEST_QUERY_CONDITION, queryCondition);
	        model.addAttribute(REQUEST_BEANS, beans);  //把结果集放入request
	        model.addAttribute(REQUEST_WRITE_BACK_FORM_VALUES, RmVoHelper.getMapFromRequest((HttpServletRequest) request));
     	 //把结果集放入request
        return "/sample/member/detailRmUser";
    }
    /**
     * 跳转到新增页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "addPage")
    public String addPage(Model model, HttpServletRequest request) {    	            
        return "/sample/member/insertRmUser";
    }
    /**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "showPage")
    public String showPage(Model model, HttpServletRequest request) {
    	//获取id
    	String id = request.getParameter(IUserConstants.REQUEST_ID);
    	//根据id查询用户
    	if(!StringHelper.isEmpty(id)){
    		RmUserVo userVo = iRmUserService.find(id);
    		model.addAttribute(REQUEST_BEAN, userVo);
    	}
        return "/sample/member/insertRmUser";
    }
    
    /**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "detail")
    public String detail(Model model, HttpServletRequest request) {
    	//获取id
    	String id = request.getParameter(IUserConstants.REQUEST_ID);
    	//根据id查询用户
    	if(!StringHelper.isEmpty(id)){
    		RmUserVo userVo = iRmUserService.find(id);
    		model.addAttribute(REQUEST_BEAN, userVo);
    	}
    	RmUserVo bean = iRmUserService.find(request.getParameter(REQUEST_ID));  //通过id获取vo
        String queryCondition="CHILD_PARTY_ID='"+bean.getId()+"'";
		//查询用户所属的组织名称
        List<RmPartyRelationVo> vos = rmPartyRelationService.queryByCondition(queryCondition, null);
        if(vos!=null && vos.size()>0){
        	bean.setAttribute1(vos.get(0).getParent_party_name());
        }
        request.setAttribute(REQUEST_BEAN, bean);  //把vo放入request
        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
            request.setAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
        }
        return "/sample/member/detailRmUser";
    }
	/**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "author")
    public String author(Model model, HttpServletRequest request) {
    	   String id = request.getParameter("id");
    		String[] role_ids = request.getParameterValues("role_name");
    		if (RmStringHelper.checkNotEmpty(id)) {
    			roleService.insertRm_party_roles(id, role_ids);
    		}
    		Map<String, Object> searchMap = null;
    		String parent_party_id = "" ;
    		if(!"3".equals(RmProjectHelper.getRmUserVo(request).getAdmin_type())){
    			if(RmProjectHelper.getRmUserVo(request).getParty_id_org()!=null){
    				//公司id
    				parent_party_id = RmProjectHelper.getRmUserVo(request).getParty_id_org();
    			}
    		}
    		String party_id = request.getParameter("id"); //用户ID
    		String party_name="";
    		if(RmStringHelper.checkNotEmpty(party_id) && !"3".equals(RmProjectHelper.getRmUserVo(request).getAdmin_type())){
    			party_name = ((IRmPartyService)RmBeanFactory.getBean(IRmPartyConstants.SERVICE_KEY)).find(party_id).getName();
    		}
    		//查询该员工赋予的角色
    		List<RmCommonVo> roleListVo = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT R.ID,PR.OWNER_ORG_ID,P.NAME from RM_ROLE R JOIN RM_PARTY_ROLE PR on R.ID=PR.ROLE_ID left join RM_PARTY P on P.OLD_PARTY_ID=PR.OWNER_ORG_ID  where R.USABLE_STATUS = '1' and PR.OWNER_PARTY_ID="+party_id);
    		Map<String, List<RmCommonVo>> mResult = new HashMap();
    		for(RmCommonVo vo:roleListVo){
    	  	  if(mResult.get(vo.getString("id")) == null) {
    	  		  mResult.put(vo.getString("id"), new ArrayList<RmCommonVo>());
    	  	  }
    	  	  mResult.get(vo.getString("id")).add(vo);
    		}
    		Map<String,String[]> mRole = new HashMap<String,String[]>();
    		for(String key:mResult.keySet()){
    			String companyName = "";
    			String companyId = "";
    	  	List<RmCommonVo> listv = mResult.get(key);
    	  	RmCommonVo sVo = listv.get(0);
    	  	String[] strs = new String[2];
    	  	for(RmCommonVo bVo:listv){
    	  		if(RmStringHelper.checkNotEmpty(bVo.getString("name")) && RmStringHelper.checkNotEmpty(bVo.getString("owner_org_id"))){
    	  			companyName += bVo.getString("name")+",";
    	  			companyId += bVo.getString("owner_org_id")+",";
    	  		}
    	  	}
    	  	if(RmStringHelper.checkNotEmpty(companyName)){
    	  		strs[0]=companyName.substring(0,companyName.length()-1);
    	  		strs[1]=companyId.substring(0,companyId.length()-1);
    	  	}
    	  	mRole.put(sVo.getString("id"),strs);
    	  }
    	  String[] roleIds = new String[mRole.size()];
    	  int j = 0;
    	  Map sWriteBack = new HashMap();
    	  for(Map.Entry<String,String[]> mr:mRole.entrySet()){
    	  	roleIds[j]=mr.getKey();
    			sWriteBack.put("company_id_"+mr.getKey(),mr.getValue().length>1 ? RmStringHelper.prt(mr.getValue()[1]):"");
    			sWriteBack.put("company_name_"+mr.getKey(),mr.getValue().length>1 ? RmStringHelper.prt(mr.getValue()[0]):"");
    			j++;
    	  }
    		//根据权限查询角色
    		//RmCommonVo cVo = RmProjectHelper.getCommonServiceInstance().doQuery("select distinct(PR.CHILD_PARTY_CODE) from RM_PARTY_RELATION PR where PR.CHILD_PARTY_ID="+userVo.getCompany().getId()).get(0);
    		List<RmCommonVo> roleList = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT ID,NAME,IS_SYSTEM_LEVEL, ROLE_CODE FROM RM_ROLE where USABLE_STATUS = '1'");
    		List<RmCommonVo> isSystemLevelList = new ArrayList<RmCommonVo>();
    		List<RmCommonVo> notSystemLevelList = new ArrayList<RmCommonVo>();
    		for(RmCommonVo vo:roleList){
    			if("1".equals(vo.getString("is_system_level"))){
    				isSystemLevelList.add(vo);
    			}else{
    				notSystemLevelList.add(vo);
    			}
    	  }
    		model.addAttribute("notSystemLevelList", notSystemLevelList);
    		model.addAttribute("isSystemLevelList", isSystemLevelList);
        return "/sample/member/auther-list";
    }
    /**
     * 从request中获得查询条件
     * @param request http请求对象
     * @return 条件Map
     */
    public static Map<String, Object> getQueryByCondition(HttpServletRequest request) {
        Map<String, Object> searchMap = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            searchMap = (Map<String, Object>)request.getAttribute(REQUEST_QUERY_CONDITION);
        } else {
           searchMap = new HashMap<String, Object>();
           searchMap.put("id", request.getParameter("id"));
           searchMap.put("name", request.getParameter("name"));
           searchMap.put("lockStatus", request.getParameter("lockStatus"));
           searchMap.put("loginId", request.getParameter("loginId"));
           searchMap.put("password", request.getParameter("password"));
           searchMap.put("authenType", request.getParameter("authenType"));
           searchMap.put("organizationId", request.getParameter("organizationId"));
           searchMap.put("employeeId", request.getParameter("employeeId"));
           searchMap.put("email", request.getParameter("email"));
           searchMap.put("adminType", request.getParameter("adminType"));
           searchMap.put("description", request.getParameter("description"));
           searchMap.put("agentStatus", request.getParameter("agentStatus"));
           searchMap.put("loginStatus", request.getParameter("loginStatus"));
           searchMap.put("lastLoginDate", request.getParameter("lastLoginDate"));
           searchMap.put("lastLoginIp", request.getParameter("lastLoginIp"));
           searchMap.put("loginSum", request.getParameter("loginSum"));
           searchMap.put("lastCustomCss", request.getParameter("lastCustomCss"));
           searchMap.put("isAffix", request.getParameter("isAffix"));
           searchMap.put("functionPermission", request.getParameter("functionPermission"));
           searchMap.put("dataPermission", request.getParameter("dataPermission"));
           searchMap.put("custom1", request.getParameter("custom1"));
           searchMap.put("custom2", request.getParameter("custom2"));
           searchMap.put("custom3", request.getParameter("custom3"));
           searchMap.put("custom4", request.getParameter("custom4"));
           searchMap.put("custom5", request.getParameter("custom5"));
           searchMap.put("customXml", request.getParameter("customXml"));
           searchMap.put("usableStatus", ISystemConstant.DICTIONARY_RM_YES_NOT_1);
           searchMap.put("modifyDate", request.getParameter("modifyDate"));
           searchMap.put("modifyIp", request.getParameter("modifyIp"));
           searchMap.put("modifyUserId", request.getParameter("modifyUserId"));
           searchMap.put("createTime", request.getParameter("createTime"));
           searchMap.put("createUserName", request.getParameter("createUserName"));
           searchMap.put("attribute1", request.getParameter("attribute1"));
           searchMap.put("attribute2", request.getParameter("attribute2"));
           searchMap.put("attribute3", request.getParameter("attribute3"));
           searchMap.put("attribute4", request.getParameter("attribute4"));
           searchMap.put("attribute5", request.getParameter("attribute5"));
           searchMap.put("delete_flag",ISystemConstant.DICTIONARY_RM_YES_NOT_0);
           searchMap.put("searchName", request.getParameter(ISystemConstant.SEARCH_NAME));
        }
        return searchMap;
    }
    /**
     * ajax 请求列表数据
     * @param model
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "onlineUserajaxList",  produces="application/json")
    @ResponseBody
    public  Map<String,Object> onlineUserajaxList(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
          boolean bLock = false;
          Map map = new HashMap();  
          Enumeration paramNames = request.getParameterNames();  
          while (paramNames.hasMoreElements()) {  
              String paramName = (String) paramNames.nextElement();  
              String[] paramValues = request.getParameterValues(paramName);  
              if (paramValues.length == 1) {  
                  String paramValue = paramValues[0];  
                   if (paramValue.length() != 0) {  
                       map.put(paramName, paramValue);  
                   }  
               }  
           }  
           Set<Map.Entry<String, String>> set = map.entrySet();  
           Map<String,Object> dataMap=new HashMap<String,Object>();
           try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
            //获取开始记录数
	    	String condition = request.getParameter(DEFAULT_CONDITION_KEY_ARRAY[0]);
	        if(condition == null) {
	            throw new RmUserOnlineRecordException(MESSAGE_NO_CONDITION_KEY);
	        }
	        String queryCondition = " " + DEFAULT_CONDITION_KEY_ARRAY[0] + "='" + condition + "'";
	        request.setAttribute(REQUEST_QUERY_CONDITION, queryCondition);
	        
	        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
	            request.setAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
	        }
	        
	        queryCondition = getQueryCondition(request);  //从request中获得查询条件
	        RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
	        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
	        List<RmUserOnlineRecordVo> beans = service.queryByCondition(queryCondition, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
	        //如果采用下边这句，就是不带翻页的，同时需要删掉list页面的page.jsp相关语句
	        //beans = service.queryByCondition(queryCondition, orderStr);  //查询全部,带排序
	        RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
	        request.setAttribute(REQUEST_QUERY_CONDITION, queryCondition);
	        request.setAttribute(REQUEST_BEANS, beans);  //把结果集放入request
	        request.setAttribute(REQUEST_WRITE_BACK_FORM_VALUES, RmVoHelper.getMapFromRequest((HttpServletRequest) request));
        	dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	        dataMap.put(ISystemConstant.PAGE_DRAW, request.getParameter(ISystemConstant.PAGE_DRAW));
	        //"recordsTotal"
        	dataMap.put(ISystemConstant.DATA, beans);
        	return dataMap;
          }catch(Exception e){
        	  e.printStackTrace();
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
        	  return dataMap;
          }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);	        
          }
    }
    /**
     * 从页面表单获取信息注入vo，并插入单条记录
     * @param request http请求对象
     * @param vo 值对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST, 
			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> insert(HttpServletRequest request, @Valid RmUserVo vo) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
	             RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
	             String uuid=vo.getAttribute2()==null?"":vo.getAttribute2();
	        	 	String md5Password=getPubParamService().signRmUserPwd(uuid, vo.getPassword());
	             vo.setPassword(md5Password);//将用户的密码加密处理
	             RmVoHelper.markCreateStamp(request,vo);  //打创建时间,IP戳
	             Timestamp ts = new Timestamp(System.currentTimeMillis());  
	             vo.setCreate_time(ts);
	             String id = null;
	             if(IOrgauthConstants.Config.isUserRelationParty.value()) {
	             	String pratyViewId = request.getParameter("view_id");
	             	String partyTypeId = request.getParameter("party_type_id");
	             	String isInherit = request.getParameter("isInherit");
	             	String[] parentPartyIds =null;
	             	String organizationIds = request.getParameter("organization_id");
	             	if(!StringHelper.isEmpty(organizationIds)){
	             		parentPartyIds = organizationIds.trim().split(",");
	             	}
	             	String[] organizationNames = request.getParameter("organization_name").split(",");
	             	//vo.setOrganization_id("");
	             	id = RmCustomOrgService.getInstance().insertParty(vo, pratyViewId, partyTypeId, parentPartyIds,organizationNames,isInherit);  //插入单条记录
	             } else {
	             	id = iRmUserService.insert(vo);  //插入单条记录
	             }
	            request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id); 
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "新增用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "新增用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 从页面表单获取信息注入vo，并更新单条记录
     * @param request http请求对象
     * @param vo 值对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "update", method = RequestMethod.POST, 
			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> update(HttpServletRequest request, @Valid RmUserVo vo) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
	            RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
	            String uuid=vo.getAttribute2()==null?"":vo.getAttribute2();
	       	 	String md5Password=getPubParamService().signRmUserPwd(uuid, vo.getPassword());
	            vo.setPassword(md5Password);//将用户的密码加密处理
	            RmVoHelper.markModifyStamp(request,vo);  //打修改时间,IP戳
	            int count = 0;
	        	if(IOrgauthConstants.Config.isUserRelationParty.value()) {
	        		String pratyViewId = request.getParameter("view_id");
	        		String partyTypeId = request.getParameter("party_type_id");
	        		String isInherit = request.getParameter("isInherit");
	        		String[] parentPartyIds = RmStringHelper.parseToArrayIgnoreEmpty(request.getParameter("organization_id"), ",");
	        		String[] parentPartyNames = RmStringHelper.parseToArrayIgnoreEmpty(request.getParameter("organization_name"), ",");
	        		String[] oldParentPartyIds = RmStringHelper.parseToArrayIgnoreEmpty(request.getParameter("oldParentPartyIds"), ",");
	        		String oldName = request.getParameter("oldName");
	        		vo.setAttribute1(request.getParameter("organization_name"));
	        		count = RmCustomOrgService.getInstance().updateParty(vo, pratyViewId,oldName, partyTypeId, parentPartyIds,oldParentPartyIds ,isInherit);  //更新单条记录
	        		//vo.setOrganization_id("");2015/4/28
	        	} else {
	        		count = iRmUserService.update(vo);  //更新单条记录
	        	}
	        	
	            request.setAttribute(EXECUTE_ROW_COUNT, count);  //sql影响的行数放入request属性
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "更新用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "更新用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 删除单条记录
     * @param request http请求对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "delete", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> delete(HttpServletRequest request) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
	        	iRmUserService.delete(request.getParameter(REQUEST_ID));
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "删除用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "删除用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 功能: 从request中获得查询条件
     *
     * @param request
     * @return
     */
    protected String getQueryCondition(HttpServletRequest request) {
        String queryCondition = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            queryCondition = request.getAttribute(REQUEST_QUERY_CONDITION).toString();
        } else {
			List<String> lQuery = new ArrayList<String>();
			
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".user_id", request.getParameter("user_id"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
        		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_time", request.getParameter("login_time_from"), RmSqlHelper.TYPE_DATE_GREATER_EQUAL));
        		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_time", request.getParameter("login_time_to"), RmSqlHelper.TYPE_DATE_LESS_EQUAL));	
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".cluster_node_id", request.getParameter("cluster_node_id"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_sign", request.getParameter("login_sign"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_ip", request.getParameter("login_ip"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_uuid", request.getParameter("login_uuid"), RmSqlHelper.TYPE_CHAR_LIKE));
				
        		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".logout_time", request.getParameter("logout_time_from"), RmSqlHelper.TYPE_DATE_GREATER_EQUAL));
        		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".logout_time", request.getParameter("logout_time_to"), RmSqlHelper.TYPE_DATE_LESS_EQUAL));	
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".logout_type", request.getParameter("logout_type"), RmSqlHelper.TYPE_CHAR_LIKE));
				
        		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".online_time", request.getParameter("online_time_from"), RmSqlHelper.TYPE_NUMBER_GREATER_EQUAL));
        		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".online_time", request.getParameter("online_time_to"), RmSqlHelper.TYPE_NUMBER_LESS_EQUAL));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".last_operation", request.getParameter("last_operation"), RmSqlHelper.TYPE_CHAR_LIKE));
				
			queryCondition = RmSqlHelper.appendQueryStr(lQuery.toArray(new String[0]));
        }
        return queryCondition;
    }
    
    
    /**
     * 得到缓存中查询条件对应的count(*)记录数，如返回-1则执行查询
     * 
     * @param queryCondition
     * @return
     */
    protected int getCount(String queryCondition) {
    	int count = RmSqlCountCache.getCount(TABLE_NAME, queryCondition);
    	if(count < 0) {
    		count = getService().getRecordCount(queryCondition);
    		RmSqlCountCache.putCount(TABLE_NAME, queryCondition, count);
    	}
    	return count;
    }
    
  public PubParamService getPubParamService() {
    	
        return (PubParamService) RmBeanFactory.getBean(PubParamService.class.getName());  //得到Service对象,受事务控制
        
    }
  /**
   * 批量生成安全密码
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "reSetPassword", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseBody
  public Map<String,Object> reSetPassword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
	  Map<String, Object> result = new HashMap<String, Object>();
	  String[] ids = RmJspHelper.getArrayFromRequest(request, REQUEST_IDS);  //从request获取多条记录id
      StringBuilder info = new StringBuilder();
      int count = 0;  //定义成功删除的记录数
      String alertStr="";
      if (ids != null && ids.length != 0) {
      	for(String id : ids) {
      		try {
      			count += iRmUserService.updatePassword(id); //生成安全密码
				} catch (Exception e) {
					RmUserVo vo = iRmUserService.find(id);
					info.append("<div>");
					info.append(vo.getLogin_id());
					info.append(", ");
					info.append(vo.getName());
					info.append(", ");
					info.append(vo.getEmail());
					info.append(", ");
					info.append(e.toString());
					info.append("</div>");
				}
      	}
      	request.setAttribute(EXECUTE_ROW_COUNT, count);  //sql影响的行数放入request属性
          if(info.length() > 0) {
          	request.getSession().setAttribute("info", info.toString());
          }
          alertStr = "成功更新" + count + "条";
          result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	      result.put(ISystemConstant.AJAX_MESSAGE, "更改用户密码成功!" );
          if((ids.length - count) > 0) {
          	alertStr += ", 失败" + (ids.length - count) + "条";
          	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
	        result.put(ISystemConstant.AJAX_MESSAGE, "更改用户密码失败!");	
          }
      }else{
      	request.setAttribute(EXECUTE_ROW_COUNT, 0);  //sql影响的行数放入request属性
      }
      RmJspHelper.goUrlWithAlert(request, response, alertStr, mapping.findForward(FORWARD_TO_QUERY_ALL).getPath());
      return result;
  }
  	
	  @RequestMapping(value = "roleList", produces = MediaType.APPLICATION_JSON_VALUE)
	  @ResponseBody
	  public static Map<String, Object> roleList(HttpServletRequest request) {
	    Map<String, Object> searchMap = new HashMap<String,Object>();
		String parent_party_id = "" ;
		if(!"3".equals(RmProjectHelper.getRmUserVo(request).getAdmin_type())){
			if(RmProjectHelper.getRmUserVo(request).getParty_id_org()!=null){
				//公司id
				parent_party_id = RmProjectHelper.getRmUserVo(request).getParty_id_org();
			}
		}
		String party_id = request.getParameter("id"); //用户ID
		String party_name="";
		if(RmStringHelper.checkNotEmpty(party_id) && !"3".equals(RmProjectHelper.getRmUserVo(request).getAdmin_type())){
			party_name = ((IRmPartyService)RmBeanFactory.getBean(IRmPartyConstants.SERVICE_KEY)).find(party_id).getName();
		}
		//查询该员工赋予的角色
		List<RmCommonVo> roleListVo = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT R.ID,PR.OWNER_ORG_ID,P.NAME from RM_ROLE R JOIN RM_PARTY_ROLE PR on R.ID=PR.ROLE_ID left join RM_PARTY P on P.OLD_PARTY_ID=PR.OWNER_ORG_ID  where R.USABLE_STATUS = '1' and PR.OWNER_PARTY_ID="+party_id);
		Map<String, List<RmCommonVo>> mResult = new HashMap();
		for(RmCommonVo vo:roleListVo){
	  	  if(mResult.get(vo.getString("id")) == null) {
	  		  mResult.put(vo.getString("id"), new ArrayList<RmCommonVo>());
	  	  }
	  	  mResult.get(vo.getString("id")).add(vo);
		}
		Map<String,String[]> mRole = new HashMap<String,String[]>();
		for(String key:mResult.keySet()){
			String companyName = "";
			String companyId = "";
	  	List<RmCommonVo> listv = mResult.get(key);
	  	RmCommonVo sVo = listv.get(0);
	  	String[] strs = new String[2];
	  	for(RmCommonVo bVo:listv){
	  		if(RmStringHelper.checkNotEmpty(bVo.getString("name")) && RmStringHelper.checkNotEmpty(bVo.getString("owner_org_id"))){
	  			companyName += bVo.getString("name")+",";
	  			companyId += bVo.getString("owner_org_id")+",";
	  		}
	  	}
	  	if(RmStringHelper.checkNotEmpty(companyName)){
	  		strs[0]=companyName.substring(0,companyName.length()-1);
	  		strs[1]=companyId.substring(0,companyId.length()-1);
	  	}
	  	mRole.put(sVo.getString("id"),strs);
	  }
	  String[] roleIds = new String[mRole.size()];
	  int j = 0;
	  Map sWriteBack = new HashMap();
	  for(Map.Entry<String,String[]> mr:mRole.entrySet()){
	  	roleIds[j]=mr.getKey();
			sWriteBack.put("company_id_"+mr.getKey(),mr.getValue().length>1 ? RmStringHelper.prt(mr.getValue()[1]):"");
			sWriteBack.put("company_name_"+mr.getKey(),mr.getValue().length>1 ? RmStringHelper.prt(mr.getValue()[0]):"");
			j++;
	  }
		//根据权限查询角色
		//RmCommonVo cVo = RmProjectHelper.getCommonServiceInstance().doQuery("select distinct(PR.CHILD_PARTY_CODE) from RM_PARTY_RELATION PR where PR.CHILD_PARTY_ID="+userVo.getCompany().getId()).get(0);
		List<RmCommonVo> roleList = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT ID,NAME,IS_SYSTEM_LEVEL, ROLE_CODE FROM RM_ROLE where USABLE_STATUS = '1'");
		List<RmCommonVo> isSystemLevelList = new ArrayList<RmCommonVo>();
		List<RmCommonVo> notSystemLevelList = new ArrayList<RmCommonVo>();
		for(RmCommonVo vo:roleList){
			if("1".equals(vo.getString("is_system_level"))){
				isSystemLevelList.add(vo);
			}else{
				notSystemLevelList.add(vo);
			}
	  }
		searchMap.put("notSystemLevelList", notSystemLevelList);
		searchMap.put("isSystemLevelList", isSystemLevelList);
		return searchMap;
	}
	  /**
	     * ajax 请求列表数据
	     * @param model
	     * @param request
	     * @return
	     * @throws IOException 
	     */
	    @RequestMapping(value = "ajaxAuthorizeResourceList")
	    @ResponseBody
	    public  Map<String,Object> ajaxAuthorizeResourceList(Model model, HttpServletRequest request, HttpServletResponse response ,String id) throws IOException{
	          boolean bLock = false;
	          Map<String,Object> dataMap=new HashMap<String,Object>();
	           try{
		    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
		    	String bs_keyword=request.getParameter("bs_keyword");
		    	
		    	
		    	RmAuthorizeVo authorize = RmAuthorizeCache.getAuthorizeByBs_keyword(bs_keyword);
		    	List<RmCommonVo> lvo = null;
		    	String party_ids[]={request.getParameter("party_id")};
		    	if(authorize!=null){
		    		String sqlSelect = "TEST_EXPRESS_ORDER.id,TEST_EXPRESS_ORDER.EXPRESS_COMPANY_NAME  AS RM_DISPLAY_COLUMN";
		    		String sql = RmOrgAuthSqlHelper.getSqlJoinAuthorize(authorize, party_ids, sqlSelect, "TEST_EXPRESS_ORDER", "");
		    		lvo = RmProjectHelper.getCommonServiceInstance().doQuery(sql);
		    	}else{
		    		lvo = new ArrayList<RmCommonVo>();		
		    	}
		    	model.addAttribute(IGlobalConstants.REQUEST_BEANS, lvo);
	        	dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        dataMap.put(ISystemConstant.PAGE_DRAW, request.getParameter(ISystemConstant.PAGE_DRAW));
		        //"recordsTotal"
	        	dataMap.put(ISystemConstant.RECORDS_TOTAL,lvo.size());
		        dataMap.put(ISystemConstant.RECORDS_FILTERED, lvo.size());
	        	dataMap.put(ISystemConstant.DATA, lvo);
	        	return dataMap;
	          }catch(Exception e){
	        	  e.printStackTrace();
	        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
	        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
	        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
	        	  return dataMap;
	          }finally{
		        //最后解锁
		        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);	        
	          }
	    }
	 
}
